﻿using MVC_basic.Models;
using MVC_basic.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using WebMatrix.WebData;
using MVC_basic.Helpers;

namespace MVC_basic.Controllers
{
    public class LoginController : Controller
    {
        private string  CookieName = "UserId";
        public LoginController()
        {
            WebSecurity_Singleton.init();
        }
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(LoginUserVM user, string returnUrl)
        {
            if (WebSecurity.Login(user.username, user.password, true))
            {
                int UserId = WebSecurity.GetUserId(user.username);
                HttpCookie myCookie = System.Web.HttpContext.Current.Request.Cookies[CookieName] ?? new HttpCookie(CookieName);
                myCookie.Value = UserId.ToString();
                myCookie.Expires = DateTime.Now.AddDays(50);
                System.Web.HttpContext.Current.Response.Cookies.Add(myCookie);
                return Redirect(returnUrl);
            }
            else
                return View();
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(User user)
        {
            WebSecurity.CreateUserAndAccount(user.username, user.password, new{email = user.email, picUrl = user.picUrl});
            return View();
        }

        public ActionResult Logout()
        {
            WebSecurity.Logout();
            HttpCookie myCookie = System.Web.HttpContext.Current.Request.Cookies[CookieName] ?? new HttpCookie(CookieName);
            myCookie.Expires = DateTime.Now.AddDays(-100);
            Response.Cookies.Add(myCookie);
            return Redirect("~");
        }

    }
}
